﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;


namespace WebCrawler
{
    /// <summary>
    /// 页面抓取类
    /// </summary>
    public class BaseAction
    {
        public WebBrowser brower = new WebBrowser();
        public HtmlDocument htmldoc;
        public BaseAction()
        {
            brower.Navigate("about:blank");
            brower.ScriptErrorsSuppressed = true;
        }

        /// <summary>
        /// 创建HtmlDocument
        /// </summary>
        /// <param name="strHtml"></param>
        public void CreateHtmlDoc(string strHtml)
        {
            htmldoc = null;
            htmldoc = brower.Document.OpenNew(true);
            htmldoc.Write(strHtml);
        }

        public void DisDoc()
        {
            if (htmldoc != null)
                brower.Dispose();
        }


        /// <summary>
        /// 获取指定类型和指定样式的结点
        /// </summary>
        /// <param name="document"></param>
        /// <param name="strTagName"></param>
        /// <param name="strClass"></param>
        /// <returns></returns>
        public List<HtmlElement> GetHtmlByClass(HtmlDocument document, string strTagName, string strClass)
        {
            HtmlElementCollection htmlList = document.GetElementsByTagName(strTagName);
            List<HtmlElement> newhtmlList = new List<HtmlElement>();
            for (int i = 0; i < htmlList.Count; i++)
            {
                if (htmlList[i].GetAttribute("ClassName").ToLower().Trim() == strClass.ToLower())
                    newhtmlList.Add(htmlList[i]);
            }
            return newhtmlList;
        }

        /// <summary>
        /// 获取指定类型和指定样式的结点
        /// </summary>
        /// <param name="document"></param>
        /// <param name="strTagName"></param>
        /// <param name="strClass"></param>
        /// <returns></returns>
        public List<HtmlElement> GetHtmlByClass(HtmlElement htmlEl, string strTagName, string strClass)
        {
            HtmlElementCollection htmlList = htmlEl.GetElementsByTagName(strTagName);
            List<HtmlElement> newhtmlList = new List<HtmlElement>();
            for (int i = 0; i < htmlList.Count; i++)
            {
                if (htmlList[i].GetAttribute("ClassName").ToLower().Trim() == strClass.ToLower())
                    newhtmlList.Add(htmlList[i]);
            }
            return newhtmlList;
        }
    }
}
